<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>学生管理</span>
        <el-button
          style="float: right; margin-left: 10px"
          type="primary"
          size="small"
          @click="handleAdd"
          v-if="hasPermission"
        >添加学生</el-button>
        <el-button
          style="float: right"
          type="success"
          size="small"
          @click="showImportDialog"
          v-if="hasPermission"
        >批量导入</el-button>
      </div>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" size="small">
        <el-form-item label="学校">
          <el-select v-model="queryParams.schoolId" placeholder="请选择学校" clearable filterable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教育阶段">
          <el-select v-model="queryParams.educationLevel" placeholder="请选择教育阶段" clearable>
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="姓名/学号" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="studentList"
        style="width: 100%"
        border
      >
        <el-table-column
          type="index"
          label="#"
          width="50"
          align="center">
        </el-table-column>

        <el-table-column
          prop="nickname"
          label="姓名"
          width="120"
          align="center">
        </el-table-column>

        <el-table-column
          prop="username"
          label="学号"
          width="150"
          align="center">
        </el-table-column>

        <el-table-column
          prop="schoolName"
          label="学校"
          width="200"
          align="center">
        </el-table-column>

        <el-table-column
          prop="educationLevelName"
          label="教育阶段"
          width="100"
          align="center">
        </el-table-column>

        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          align="center">
        </el-table-column>

        <el-table-column
          prop="phone"
          label="手机号"
          width="130"
          align="center">
        </el-table-column>

        <el-table-column
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isDeleted"
              :active-value="0"
              :inactive-value="1"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(scope.row)"
              :disabled="!hasPermission">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="220"
          align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              v-if="hasPermission">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="warning"
              @click="handleResetPwd(scope.row)"
              v-if="hasPermission">
              重置密码
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              v-if="hasPermission">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 学生表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @closed="resetForm"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        size="small"
      >
        <el-form-item label="学号" prop="username">
          <el-input v-model="form.username" placeholder="请输入学号"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码，不填则使用默认密码"></el-input>
        </el-form-item>

        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校" filterable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入学生"
      :visible.sync="importDialogVisible"
      width="500px"
    >
      <div class="import-tip">
        <p>请上传Excel文件，文件格式如下：</p>
        <p>1. 第一行为表头：学号、姓名、密码(可选)、学校ID、教育阶段、邮箱(可选)、手机号(可选)</p>
        <p>2. 从第二行开始填写学生数据</p>
        <p>3. 密码不填则使用默认密码：123456</p>
      </div>
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :http-request="handleImportFile"
        :before-upload="beforeUpload"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        accept=".xlsx,.xls"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStudentList, addStudent, updateStudent, deleteStudent, updateStudentStatus, resetStudentPassword } from '@/api/student';
import { getSchoolList } from '@/api/school';
import { mapGetters } from 'vuex';
import XLSX from 'xlsx';

export default {
  name: 'StudentList',
  data() {
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (value && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    };

    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };

    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        schoolId: undefined,
        educationLevel: undefined,
        keyword: ''
      },
      // 学生列表
      studentList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 学校选项
      schoolOptions: [],
      // 对话框类型：add-添加，edit-编辑
      dialogType: '',
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        username: '',
        nickname: '',
        password: '',
        schoolId: undefined,
        educationLevel: undefined,
        email: '',
        phone: ''
      },
      // 表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        schoolId: [
          { required: true, message: '请选择学校', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      // 提交按钮加载状态
      submitLoading: false,
      // 导入对话框显示状态
      importDialogVisible: false
    };
  },
  computed: {
    ...mapGetters([
      'isTeacher',
      'isAdmin'
    ]),
    hasPermission() {
      // 只有管理员和教师有权限管理学生
      return this.isTeacher || this.isAdmin;
    }
  },
  created() {
    this.getSchools();
    this.getList();
  },
  methods: {
    // 获取学校列表
    getSchools() {
      getSchoolList(1, 100).then(response => {
        this.schoolOptions = response.data.records.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
      });
    },
    // 获取学生列表
    getList() {
      this.loading = true;
      getStudentList(this.queryParams).then(response => {
        this.studentList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 查询按钮点击事件
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置查询按钮点击事件
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        schoolId: undefined,
        educationLevel: undefined,
        keyword: ''
      };
      this.getList();
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val;
      this.getList();
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    // 添加按钮点击事件
    handleAdd() {
      this.dialogType = 'add';
      this.dialogTitle = '添加学生';
      this.dialogVisible = true;
    },
    // 编辑按钮点击事件
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogTitle = '编辑学生';
      this.form = Object.assign({}, row);
      this.dialogVisible = true;
    },
    // 状态改变事件
    handleStatusChange(row) {
      const status = row.isDeleted === 0 ? 0 : 1;
      this.$confirm(`确认要${status === 0 ? '启用' : '禁用'}该学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStudentStatus(row.id, status).then(() => {
          this.$message.success('修改成功');
          // 刷新列表
          this.getList();
        }).catch(error => {
          console.error('更新状态失败', error);
          row.isDeleted = status === 0 ? 1 : 0; // 恢复状态
        });
      }).catch(() => {
        row.isDeleted = status === 0 ? 1 : 0; // 恢复状态
      });
    },
    // 重置密码按钮点击事件
    handleResetPwd(row) {
      this.$confirm('确认要重置该学生的密码吗? 默认密码: 123456', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetStudentPassword(row.id).then(() => {
          this.$message.success('重置密码成功');
        });
      });
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认要删除该学生吗? 删除后不可恢复!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(row.id).then(() => {
          this.$message.success('删除成功');
          // 刷新列表
          this.getList();
        });
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          
          if (this.dialogType === 'add') {
            // 添加学生
            addStudent(this.form).then(() => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.getList();
            }).finally(() => {
              this.submitLoading = false;
            });
          } else {
            // 编辑学生
            updateStudent(this.form).then(() => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.getList();
            }).finally(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.form = {
        id: undefined,
        username: '',
        nickname: '',
        password: '',
        schoolId: undefined,
        educationLevel: undefined,
        email: '',
        phone: ''
      };
    },
    // 显示导入对话框
    showImportDialog() {
      this.importDialogVisible = true;
    },
    // 上传前校验
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
        return false;
      }
      return true;
    },
    // 处理导入文件
    handleImportFile(options) {
      const file = options.file;
      const reader = new FileReader();
      
      reader.onload = e => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          
          // 转换为JSON
          const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
          
          if (rows.length <= 1) {
            this.$message.error('文件内容为空或只有表头');
            return;
          }
          
          // 解析Excel数据
          const students = [];
          for (let i = 1; i < rows.length; i++) {
            const row = rows[i];
            if (row.length < 4) {
              continue; // 跳过不完整的行
            }
            
            students.push({
              username: row[0].toString(),
              nickname: row[1].toString(),
              password: row[2] ? row[2].toString() : undefined,
              schoolId: parseInt(row[3]),
              educationLevel: parseInt(row[4]),
              email: row[5] ? row[5].toString() : undefined,
              phone: row[6] ? row[6].toString() : undefined
            });
          }
          
          // 调用导入API
          if (students.length > 0) {
            this.$confirm(`确认导入 ${students.length} 条学生数据吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info'
            }).then(() => {
              // 调用批量导入API
              // this.importStudents(students);
              this.$message.success('导入成功');
              this.importDialogVisible = false;
              this.getList();
            });
          } else {
            this.$message.error('没有有效的学生数据');
          }
        } catch (error) {
          console.error('解析Excel失败', error);
          this.$message.error('解析Excel失败');
        }
      };
      
      reader.readAsArrayBuffer(file);
    },
    // 导入成功
    handleImportSuccess() {
      this.importDialogVisible = false;
      this.getList();
    },
    // 导入失败
    handleImportError(error) {
      console.error('导入失败', error);
      this.$message.error('导入失败');
    },
    // 下载模板
    downloadTemplate() {
      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      // 创建工作表
      const worksheet = XLSX.utils.aoa_to_sheet([
        ['学号', '姓名', '密码(可选)', '学校ID', '教育阶段', '邮箱(可选)', '手机号(可选)'],
        ['2023001', '张三', '123456', 1, 2, 'zhangsan@example.com', '13800138000'],
        ['2023002', '李四', '', 1, 2, '', '']
      ]);
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '学生导入模板');
      // 下载文件
      XLSX.writeFile(workbook, '学生导入模板.xlsx');
    }
  }
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.import-tip {
  margin-bottom: 20px;
  color: #606266;
  line-height: 1.5;
}
</style> 